package wo.xsys.service.impl;

import javax.annotation.Resource;
import javax.transaction.Transactional;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import wo.common.entity.WoPage;
import wo.common.util.WoUtil;
import wo.xsys.dto.MenuDto;
import wo.xsys.po.Menu;
import wo.xsys.repository.MenuRepository;
import wo.xsys.service.MenuService;

/**
 * PO实体Menu对应的Service接口实现类.
 * @author cailei
 */
@Service
@Transactional
public class MenuServiceImpl implements MenuService {

	/**
	 * 使用日志打印框架.
	 */
	private final static Logger LOG = LogManager.getLogger(MenuServiceImpl.class);
	
	/**
	 * 注入MenuRepository.
	 */
	@Resource // @Autowired
	private MenuRepository menuRepository;

	/**
	 * 获取分页数据
	 * @param searchContent
	 * @param selectedIds
	 * @param start 分页开始的行索引，0开始
	 * @param limit 分页最大行数
	 * @return
	 */
	@Override
	public WoPage<MenuDto> getPageData(String searchContent, String[] selectedIds, Long start, Long limit) {
		// 从dao获取数据
		Pageable pageInput = PageRequest.of(start.intValue() / limit.intValue(), limit.intValue());
		Page<Menu> pageData = null;
		if (WoUtil.isEmpty(searchContent)) {
			pageData = menuRepository.findAll(pageInput);
		} else {
			pageData = menuRepository.findAllByNameLike("%" + searchContent + "%", pageInput);
		}
		// 将PO转化为DTO
		WoPage<MenuDto> pr = MenuDto.getPageData(pageData.getContent(), pageData.getTotalElements(), selectedIds);
		return pr;
	}

	/**
	 * 创建
	 * @param dto 
	 */
	@Override
	public void create(MenuDto dto) {
		Menu po = dto.createPO();
		this.menuRepository.save(po);
	}

	/**
	 * 更新对象
	 * @param dto
	 */
	@Override
	public void update(MenuDto dto) {
		Menu po = menuRepository.findById(dto.getId()).get();
		dto.updatePO(po);
		this.menuRepository.save(po);
	}
	
	/**
	 * 根据ids值删除多个对象
	 * @param ids
	 */
	@Override
	public void delete(String[] ids) {
		for (String id : ids) {
			this.menuRepository.deleteById(id);
		}
	}
}
